<template>
  <div class="a3-page">
    <div class="tool-view">
      <n-scrollbar x-scrollable>
        <div class="tool-l">
          <span>站点名称</span>
          <n-select
            placeholder="选择站点名称"
            style="width: 120px"
            v-model:value="params.modelId"
            :options="stationList"
            @update:value="GetAllStationInfoFun"
          />
          <span>OP属性</span>
          <n-select
            placeholder="选择OP属性"
            style="width: 120px"
            v-model:value="params.stationId"
            :options="OPList"
          />
          <span>产品名称</span>
          <n-select
            placeholder="选择产品名称"
            style="width: 120px"
            v-model:value="params.productName"
            :options="productNameList"
            @update:value="GetProductSNListFun"
          />
          <span>SN码</span>
          <n-select
            placeholder="选择SN码"
            style="width: 120px"
            v-model:value="params.productSN"
            :options="productSNList"
          />
          <span>时间</span>
          <n-config-provider :locale="zhCN" :date-locale="dateZhCN">
            <n-date-picker
              style="width: 260px"
              v-model:value="range"
              type="daterange"
              clearable
              @update:formatted-value="timeChange"
              :is-date-disabled="disablePreviousDate"
            />
          </n-config-provider>
        </div>
      </n-scrollbar>
      <n-button
        style="margin: 0 12px"
        type="success"
        :disabled="!isQuery"
        @click="GetPageB1DataFun"
      >
        查询
      </n-button>
      <div class="tool-r" @click="GetAllPropertyFun">
        <n-button color="#EE9708">编辑</n-button>
      </div>
    </div>
    <div class="table-view">
      <div v-if="stepsList.length > 0" class="table-left">
        <div class="title">执行日志</div>
        <n-scrollbar style="max-height: calc(100% - 30px)">
          <n-steps vertical :current="stepsList.length" status="finish">
            <template #finish-icon>
              <icons class="icon" name="step" />
            </template>
            <n-step
              v-for="step in stepsList"
              :key="step.id"
              :title="step.remark"
            >
              <template #default>
                <!-- <div class="step-desc">
                  {{ step.remark }}
                </div> -->
                <div
                  v-for="(text, i) in step.partsName"
                  :key="i"
                  class="step-desc"
                >
                  {{ text }}
                </div>
              </template>
            </n-step>
          </n-steps>
        </n-scrollbar>
      </div>
      <n-scrollbar style="max-height: calc(100% - 10px)">
        <div class="table-right">
          <div v-if="echarlsList.length === 0 && showSpin" class="load">
            <n-spin :show="showSpin">
              <template #description> 加载中 </template>
            </n-spin>
          </div>
          <div v-for="echart in echarlsList" :key="echart.id" class="card">
            <div class="title">{{ echart.propertyName }}</div>
            <div class="card-content">
              <Circular
                v-if="echart.chartType === '饼状图'"
                :data="echart.datas"
              />
              <Columnar
                v-else-if="echart.chartType === '柱状图'"
                :data="echart.datas"
              />
              <Polyline
                v-else-if="echart.chartType === '折线图'"
                :data="echart.datas"
              />
              <div v-else>{{ echart.chartType }}</div>
            </div>
          </div>
        </div>
      </n-scrollbar>
    </div>
  </div>
  <n-modal
    :mask-closable="false"
    class="more-dialog"
    v-model:show="openMore"
    preset="dialog"
    :show-icon="false"
    :on-close="closeWin"
    transform-origin="center"
    style="background: #60676c; color: #fff; width: 700px"
  >
    <template #header>
      <div class="title-font">设置绑定数据</div>
    </template>
    <n-scrollbar style="max-height: calc(90vh - 200px)">
      <div class="notice-info">
        <div v-for="item in propertyArr" :key="item.id" class="type-option">
          <div class="title">{{ item.value }}</div>
          <div
            v-for="chidren in item.datas"
            :key="chidren.propertyName"
            class="div"
          >
            <n-checkbox
              size="large"
              v-model:checked="chidren.checked"
              @update:checked="checkedFun($event, chidren)"
            >
              {{ chidren.propertyName }}
            </n-checkbox>
            <div v-if="chidren.checked" class="num">
              <n-input
                type="text"
                style="width: 50px"
                v-model:value="chidren.sort"
                :allow-input="onlyAllowNumber"
                placeholder="排序"
              />
            </div>
            <div
              class="check-Box-view"
              :class="chidren.checked ? '' : 'disabled'"
            >
              <div
                v-for="el in chidren.chartType"
                :class="chidren.active === el ? 'active' : ''"
                :key="el"
                class="btn"
                @click="chidren.active = el"
              >
                {{ el }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </n-scrollbar>
    <div class="footer">
      <n-button class="btn" @click="InsertA2BindDataFun">保存</n-button>
    </div>
  </n-modal>
</template>

<script lang="ts" setup>
import { computed, watch, ref } from "vue";
import { useRoute } from "vue-router";
import { today } from "@/tools/radom";
import Circular from "@/components/Echarts/Circular.vue"; //饼图
import Columnar from "@/components/Echarts/Columnar.vue"; //柱状图
import Polyline from "@/components/Echarts/Polyline.vue"; //折线
import {
  GetStationConfiguration,
  GetAllStationInfo,
  GetProductNameList,
  GetProductSNList,
  GetPageA2Name,
  GetAllProperty,
  PageB1DataBind,
  GetPageB1Data,
} from "@/server";
import { zhCN, dateZhCN } from "naive-ui";
import { useAppStore } from "@/store/modules/user";
import { mapStore } from "@/store/modules/map";
const route = useRoute();
const modelId = computed(() => route.params.id);
const store = useAppStore();
const openMore = ref(false);
const stationList = ref([]) as any; //站台列表
const OPList = ref([]) as any; //站台列表
const showSpin = ref(false);
const params = ref({
  modelId: null,
  stationId: null,
  productName: null,
  productSN: null,
  startTime: today(),
  endTime: today(),
}) as any;
const stepsList = ref([]) as any; //站台列表
const productNameList = ref([]) as any; //产品名称列表;
const productSNList = ref([]) as any; //产品SN码列表
const echarlsList = ref([]) as any; //产品SN码列表
const propertyArr = ref([]) as any;
const range = ref<[number, number]>([Date.now(), Date.now()]);
const timeChange = (e: any) => {
  params.value.startTime = e[0];
  params.value.endTime = e[1];
};
const closeWin = () => {
  openMore.value = false;
};
const isQuery = computed(() => {
  const { modelId, stationId, productName, productSN, startTime, endTime } =
    params.value;
  return (
    modelId && stationId && productName && productSN && startTime && endTime
  );
});
watch(
  () => modelId.value,
  () => {
    params.value = {
      modelId: null,
      stationId: null,
      productName: null,
      productSN: null,
      startTime: today(),
      endTime: today(),
    };
    GetPageA2NameFun();
    GetProductNameListFun();
  }
);
//查询站台详情
const GetStationConfigurationFun = async () => {
  echarlsList.value = [];
  const res: any = await GetStationConfiguration({
    Id: params.value.stationId,
  });
  if (res.result.isSuccess) {
    stepsList.value = res.result.result.steps;
  } else {
    store.error(res.result.message); // 错误提示
  }
};
const onlyAllowNumber = (value: string) => {
  return !value || /^\d+$/.test(value);
};
const openMoreWin = () => {
  // modelType.value = type;
  let list = JSON.parse(JSON.stringify(propertyList.value));
  let list2: any = [];
  // if (type === "2-2") {
  //   list2 = A2List.value;
  // } else if (type === "2-3") {
  //   list2 = A3List.value;
  // } else if (type === "2-4") {
  //   list2 = A4List.value;
  // }
  list2.forEach((listItem: any) => {
    const [prefix, suffix] = listItem.propertyName.split("-");
    const matchingItem = list.find((item: any) => prefix === item.value);
    if (matchingItem) {
      const matchingData = matchingItem.datas.find(
        (data: any) => data.propertyName === suffix
      );
      if (matchingData) {
        matchingData.checked = true;
        matchingData.active = listItem.chartType;
      }
    }
  });
  list = list.map((m: any) => {
    m.datas = m.datas.map((e: any) => {
      if (!e.sort) {
        e.sort = 0 + "";
      } else {
        e.sort = e.sort + "";
      }
      return e;
    });
    return m;
  });
  propertyArr.value = list;
  openMore.value = true;
};
const InsertA2BindDataFun = async () => {
  // 转换为新格式
  const deviceList = propertyArr.value
    .map((item: any) => {
      const data = item.datas
        .filter((dataItem: any) => dataItem.checked)
        .map((dataItem: any) => ({
          sort: dataItem.sort + "",
          deviceCode: item.value,
          propertyName: dataItem.propertyName,
          chartType: dataItem.active || dataItem.chartType[0], // 使用 active，如果不存在则使用 chartType 的第一个值
        }));

      return {
        data,
      };
    })
    .filter((item: any) => item.data.length > 0); // 过滤掉没有数据的项;
  // 提取 data 属性并合并为一维数组
  const flatArray: any = deviceList.flatMap((item: any) => item.data);
  console.log(JSON.stringify(flatArray));
  const param = {
    modelId: params.value.modelId,
    stationId: params.value.stationId,
    datas: flatArray,
  };
  const res: any = await PageB1DataBind(param);
  if (res.result.isSuccess) {
    store.success(res.result.message); // 错误提示
    closeWin();
    GetPageB1DataFun();
  } else {
    store.error(res.result.message); // 错误提示
  }
};
const lock = ref(false);
const unLock = () => {
  setTimeout(() => {
    lock.value = false;
  }, 1000);
};
//查询数据
const GetPageB1DataFun = async () => {
  if (lock.value || !isQuery.value) {
    return false;
  }
  GetStationConfigurationFun();
  lock.value = true;
  showSpin.value = true;
  const res: any = await GetPageB1Data(params.value);
  if (res.result.isSuccess) {
    echarlsList.value = res.result.result;
    if (echarlsList.value.length === 0) {
      store.info("未查询到数据"); // 错误提示
    }
    unLock();
    showSpin.value = false;
  } else {
    unLock();
    showSpin.value = false;
    store.error(res.result.message); // 错误提示
  }
};
const disablePreviousDate = (ts: number) => {
  return ts > Date.now();
};
const checkedFun = (bool: boolean, item: any) => {
  if (bool) {
    item.active = item.chartType[0];
  } else {
    item.active = "";
  }
};
const propertyList = ref([]) as any;
const GetAllPropertyFun = async () => {
  let stationName = "";
  const station = OPList.value.find(
    (e: any) => e.id === params.value.stationId
  );
  if (station) {
    stationName = station.stationName;
  } else {
    store.info("请线选择OP属性"); // 错误提示
    return false;
  }
  const res: any = await GetAllProperty({ stationName: stationName });
  if (res.result.isSuccess) {
    let list = res.result.result.map((e: any) => {
      return { value: e.deviceCode, label: e.deviceCode, datas: e.datas };
    });

    let list2: any = echarlsList.value;
    list2.forEach((listItem: any) => {
      const [prefix, suffix] = listItem.propertyName.split("-");
      const matchingItem = list.find((item: any) => prefix === item.value);
      if (matchingItem) {
        const matchingData = matchingItem.datas.find(
          (data: any) => data.propertyName === suffix
        );
        if (matchingData) {
          matchingData.sort = listItem.sort;
          matchingData.checked = true;
          matchingData.active = listItem.chartType;
        }
      }
    });
    list = list.map((m: any) => {
      m.datas = m.datas.map((e: any) => {
        if (!e.sort) {
          e.sort = 0;
        }
        return e;
      });
      return m;
    });
    propertyList.value = list;
    openMoreWin();
  } else {
    store.error(res.result.message); // 错误提示
  }
};
//获取所有站点配置
const GetAllStationInfoFun = async () => {
  const res: any = await GetAllStationInfo({
    modelId: params.value.modelId,
  });
  if (res.result.isSuccess) {
    params.value.stationId = null;
    OPList.value = res.result.result.map((e: any) => {
      e.value = e.id;
      e.label = e.stationName;
      return e;
    });
    if (OPList.value.length > 0) {
      params.value.stationId = OPList.value[0].id;
      // GetStationConfigurationFun();
    }
  } else {
    store.error(res.result.message); // 错误提示
  }
};

//获取产品名称列表
const GetProductSNListFun = async () => {
  const res: any = await GetProductSNList({
    productName: params.value.productName,
  });
  if (res.result.isSuccess) {
    params.value.productSN = null;
    productSNList.value = res.result.result.map((e: any) => {
      return { value: e, label: e, id: e };
    });
  } else {
    store.error(res.result.message); // 错误提示
  }
};
//获取产品名称列表
const GetProductNameListFun = async () => {
  const res: any = await GetProductNameList({});
  if (res.result.isSuccess) {
    productNameList.value = res.result.result.map((e: any) => {
      return { value: e, label: e, id: e };
    });
  } else {
    store.error(res.result.message); // 错误提示
  }
};

//获取初始化数据1
const GetPageA2NameFun = async () => {
  const res: any = await GetPageA2Name(params.value);
  if (res.result.isSuccess) {
    stationList.value = res.result.result.map((e: any) => {
      e.value = e.modelId;
      e.label = e.name;
      return e;
    });
  } else {
    store.error(res.result.message); // 错误提示
  }
};
GetPageA2NameFun();
GetProductNameListFun();
</script>

<style lang="less" scoped>
.a3-page {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #ffffff;
  .tool-view {
    display: flex;
    height: 60px;
    align-items: center;
    justify-content: space-between;
    background: #e3e3e3;
    backdrop-filter: blur(32px);

    .tool-l {
      min-width: 1200px;
      display: flex;
      align-items: center;
      flex: 1;
      height: 60px;

      span {
        font-size: 18px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        color: #1c262d;
        line-height: 25px;
        margin: 0 12px 0 20px;
      }
    }

    .tool-r {
      padding-right: 20px;
    }
  }
  .table-view {
    padding: 0 10px;
    height: calc(100% - 60px);
    display: flex;
    .table-left {
      width: 240px;
      padding: 15px 25px;
      .title {
        width: 160px;
        height: 32px;
        background: #5d6a73;
        box-shadow: 0px 0px 1px 0px rgba(0, 0, 0, 0.08),
          0px 1px 3px 0px rgba(25, 15, 15, 0.07),
          0px 3px 5px 0px rgba(0, 0, 0, 0.05);
        font-size: 14px;
        font-family: SourceHanSansCN, SourceHanSansCN;
        font-weight: bold;
        color: #ffffff;
        line-height: 32px;
        margin-bottom: 30px;
      }
    }
    .table-right {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
      .load {
        height: 50vh;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .card {
        position: relative;
        width: 50%;
        padding-left: 15px;
        height: 300px;
        min-width: 500px;
        padding: 15px 0;
        border-bottom: 10px solid #dbdbdb;
        .title {
          left: 0;
          position: absolute;
          background: #5d6a73;
          display: inline-block;
          padding: 5px 20px;
          box-shadow: 0px 0px 1px 0px rgba(0, 0, 0, 0.08),
            0px 1px 3px 0px rgba(25, 15, 15, 0.07),
            0px 3px 5px 0px rgba(0, 0, 0, 0.05);
          font-size: 14px;
          font-family: SourceHanSansCN, SourceHanSansCN;
          font-weight: bold;
          color: #ffffff;
        }
        .card-content {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
.step-desc {
  font-size: 17px;
  font-family: SourceHanSansCN, SourceHanSansCN;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
  line-height: 33px;
  text-align: left;
}
.more-dialog {
  .title-font {
    font-size: 24px;
    color: #02a8ae;
  }
  .notice-info {
    margin: 20px 0 40px;
    .title {
      font-size: 20px;
      margin-bottom: 10px;
      color: #b2b2b2;
    }
    .type-option {
      width: 100%;
      .div {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;
      }
      :deep(.n-checkbox__label) {
        color: #ffffff;
      }
      .num {
        flex: 1;
        display: flex;
        justify-content: flex-end;
        padding-right: 20px;
        :deep(.n-input) {
          background: none;
          text-align: center;
          input {
            color: #ffffff;
          }
        }
      }
      .check-Box-view {
        &.disabled {
          pointer-events: none;
          opacity: 0.3;
        }
        display: flex;
        width: 50%;
        padding: 2px;
        .btn {
          &:hover {
            background: #02a8ae;
          }
          &.active {
            background: #01c0e4;
          }
          cursor: pointer;
          flex: 1;
          font-size: 14px;
          /* background: #f5f5f5; */
          color: #ffffff;
          margin-right: 5px;
          display: flex;
          justify-content: center;
          padding: 5px;
          border: 1px solid #838383;
          box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.08),
            0px 2px 5px 0px rgba(25, 15, 15, 0.07),
            0px 5px 8px 0px rgba(0, 0, 0, 0.05);
        }
      }
    }
  }
  .footer {
    margin-top: 10px;
    display: flex;
    justify-content: center;
    .btn {
      width: 100px;
      height: 36px;
      font-size: 18px;
      color: #fff;
      background: #02a8ae;
    }
  }
}
:deep(.n-step-indicator) {
  background: #02a8ae;
  box-shadow: 0 0 0 1px #02a8ae;
}
:deep(.n-step-splitor) {
  background: rgba(0, 0, 0, 0.15);
}
:deep(.n-step-content-header) {
  margin-top: 0 !important;
}
:deep(.n-step-content-header__title) {
  font-size: 22px;
  font-family: SourceHanSansCN, SourceHanSansCN;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  line-height: 33px;
}
</style>
